<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showApplication"
      width="600"
      @close="closeDrawer"
    >
      <el-form
        ref="bmForm"
        :model="bmForm"
        :rules="rules"
        label-width="auto"
        label-suffix="："
      >
        <el-form-item :label="$t('message.kclx')" prop="courseType">
          <el-radio
            v-model="bmForm.courseType"
            label="4"
            @change="changeCourseType"
          >{{ $t('message.sjk') }}</el-radio>
          <el-radio
            v-model="bmForm.courseType"
            label="5"
            @change="changeCourseType"
          >{{ $t('message.cgk') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('message.kcmc')" prop="courseId">
          <el-select
            v-model="bmForm.courseId"
            filterable
            :placeholder="$t('message.qxz') + $t('message.kc')"
            style="width: 100%"
            @change="getreserveClassInfoPC"
          >
            <el-option
              v-for="item in perKcList"
              :key="item.courseId"
              :label="item.courseName"
              :value="item.courseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="acticeKc && acticeKc.price">
          <div class="acticeKc_wrap">
            <div class="item">{{ $t('message.kcjg') }}：<span class="red">{{ $t('message.rmbfh') }}{{ acticeKc.price }}{{ $t('message.qi') }}</span></div>
            <div v-if="acticeKc.courseNum" class="item">{{ $t('message.zkss') }}：{{ acticeKc.courseNum }}{{ $t('message.keshi') }}</div>
            <div v-if="acticeKc.dateLimit" class="item">{{ $t('message.bmjz2') }}：{{ acticeKc.dateLimit }}</div>
            <div v-if="acticeKc.beginTime" class="item">{{ $t('message.kksj') }}：{{ acticeKc.beginTime }}</div>
            <div v-if="acticeKc.numLimit" class="item">
              {{ $t('message.rsxz') }}：{{ acticeKc.numLimit == '1' ? $t('message.bx') : acticeKc.numLow == '1' && acticeKc.numUp == '1' ? $t('message.jxyr') : acticeKc.numLow + '~' + acticeKc.numUp + $t('message.ren') }}
            </div>
            <div v-if="acticeKc.numJoin" class="item">{{ $t('message.ybms') }}：<span class="primaryColor">{{ acticeKc.numJoin }}{{ $t('message.ren') }}</span></div>
            <div v-if="bmForm.courseType == '5' && acticeKc.numLimit == '2' && acticeKc.numUp <= acticeKc.numJoin" class="item red fs_12 w400">{{ $t('message.dqkcbmrsydsx') }}</div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.yhxx')" prop="memberId">
          <div>
            <MemberSearch
              ref="memberSearchRef"
              @clear="tgMemberClear"
              @select="tgMemberSelect"
            />
          </div>
        </el-form-item>
        <el-form-item v-if="tgMemberInfo.id" :label="$t('message.xyxx')" prop="members">
          <div style="display: flex">
            <el-select
              v-model="bmForm.members"
              multiple
              collapse-tags
              filterable
              :placeholder="$t('message.qxz') + $t('message.xueyuan')"
              style="flex: 1"
              @change="getreserveClassInfoPC"
            >
              <el-option
                v-for="item in members"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button
              class="ml20"
              type="primary"
              @click="showAddBtn"
            >{{ $t('message.xzxy') }}</el-button>
          </div>
        </el-form-item>
        <el-form-item
          v-if="tgMemberInfo.id && showAdd"
          :label="$t('message.xzxy')"
          prop="name"
        >
          <div style="display: flex">
            <el-input
              v-model="xyForm.name"
              :placeholder="$t('message.qsr') + $t('message.xyxm')"
              style="flex: 1"
            />
            <el-select
              v-model="xyForm.sex"
              class="ml20"
              :placeholder="$t('message.qxz') + $t('message.sex')"
              style="flex: 1"
            >
              <el-option
                v-for="item in sexList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button
              v-preventReClick
              class="ml20"
              type="primary"
              @click="sideBtn"
            >{{ $t('message.bcxy') }}</el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="bmForm.courseType == '4'" :label="$t('message.yyrq')">
          <el-date-picker
            v-model="bmForm.day"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('message.qxz') + $t('message.yyrq')"
            style="width: 100%"
            @change="getreserveClassInfoPC"
          />
        </el-form-item>
        <template v-if="bmForm.courseType == '4'">
          <el-form-item :label="$t('message.jiaolian')" prop="teacherId">
            <el-select
              v-model="bmForm.teacherId"
              :placeholder="$t('message.qxz') + $t('message.jiaolian')"
              style="width: 100%"
              filterable
              @change="getreserveClassInfoPC"
            >
              <el-option
                v-for="item in teachList"
                :key="item.teacherId"
                :label="item.teacherName"
                :value="item.teacherId"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('message.kysd')" prop="time">
            <el-select
              v-model="bmForm.time"
              multiple
              :placeholder="$t('message.qxzskjlsksjd')"
              style="width: 100%"
              @change="getreserveClassInfoPC"
            >
              <el-option
                v-for="(item, index) in timeList"
                :key="index"
                :label="`${item.startTime}~${item.endTime}${item.reserveNum ? '（' + $t('message.ybm') + item.reserveNum + $t('message.ren') + ')' : ''}`"
                :value="index"
              />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item :label="$t('message.kcjg')" prop="price">
          <el-input v-model="bmForm.price" disabled style="width: 100%" />
        </el-form-item>
        <el-form-item>
          <el-button @click="closeDrawer">{{ $t('message.qx') }}</el-button>
          <el-button
            :loading="subLoading"
            type="primary"
            @click="confirmAction"
          >{{ $t('message.qzf') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="$t('message.xzxy')"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showStudent"
    >
      <el-form
        ref="formStudent"
        :model="formStudent"
        label-width="auto"
        :rules="ruleb"
        label-suffix="："
      >
        <el-form-item prop="name" :label="$t('message.xyxm')">
          <el-input
            v-model="formStudent.name"
            maxlength="50"
            :placeholder="$t('message.qsr') + $t('message.xyxm')"
            clearable
          />
        </el-form-item>
        <el-form-item prop="sex" :label="$t('message.xyxb')">
          <el-select
            v-model="formStudent.sex"
            style="width: 100%"
            :placeholder="$t('message.qxz') + $t('message.sex')"
          >
            <el-option value="1" :label="$t('message.nan')" />
            <el-option value="2" :label="$t('message.nv')" />
            <el-option value="0" :label="$t('message.bm')" />
          </el-select>
        </el-form-item>
        <el-form-item prop="birthday" :label="$t('message.csrq')">
          <el-date-picker
            v-model="formStudent.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('message.qxz') + $t('message.csrq')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="idCard" :label="$t('message.sfzh')">
          <el-input
            v-model="formStudent.idCard2"
            maxlength="18"
            :placeholder="$t('message.qsr') + $t('message.xysfzh')"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showStudent = false">{{ $t('message.qx') }}</el-button>
        <el-button :loading="subStuLoading" type="primary" @click="onSubmitb">{{ $t('message.baocun') }}</el-button>
      </div>
    </el-dialog>
    <orderDialog
      v-if="isShowOrder"
      ref="orderRef"
      @studentAddSuccess="showApplication = false"
      @orderSuccess="orderSuccess"
      @openSuccess="subLoading = false"
    />
  </div>
</template>

<script>
import {
  teacherGmList, publishCourseList, studentListByMember, studentAdd, reserveClassInfoPC
} from '@/api'
import store from '@/store'
import orderDialog from '@/components/order'
import MemberSearch from '@/components/MemberSearch'
import dayjs from 'dayjs'
export default {
  components: {
    orderDialog,
    MemberSearch
  },
  data() {
    return {
      title: '',
      showApplication: false,
      showStudent: false,
      isShowOrder: false,
      subLoading: false,
      subStuLoading: false,
      modalDialog: store.getters.dialog,
      bmForm: {
        courseType: '4'
      },
      tgMemberInfo: {},
      formStudent: {},
      perKcList: [],
      acticeKc: {},
      members: [],
      teachList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        }
      },
      sexList: [
        { value: '0', label: this.$t('message.bm') },
        { value: '1', label: this.$t('message.nan') },
        { value: '2', label: this.$t('message.nv') }
      ],
      ruleb: {
        name: [{ required: true, message: this.$t('message.qsr') + this.$t('message.xyxm'), trigger: 'blur' }]
      },
      xyForm: {},
      timeList: [],
      pdSj: false,
      rules: {
        courseId: [{ required: true, message: this.$t('message.qxz') + this.$t('message.kc'), trigger: 'change' }],
        members: [{ required: true, message: this.$t('message.qxz') + this.$t('message.xueyuan'), trigger: 'change' }],
        day: [{ required: true, message: this.$t('message.qxz') + this.$t('message.skrq'), trigger: 'change' }],
        time: [{ required: true, message: this.$t('message.qxzskjlsksjd'), trigger: 'change' }],
        teacherId: [{ required: true, message: this.$t('message.qxz') + this.$t('message.skjl2'), trigger: 'change' }],
        memberId: [{ required: true, message: this.$t('message.qxz') + this.$t('message.hy'), trigger: 'change' }]
      },
      showAdd: false
    }
  },
  created() {

  },
  methods: {
    changeCourseType() {
      this.$set(this.bmForm, 'courseId', '')
      this.acticeKc = {}
      this.getKcList()
    },
    showClick() {
      this.showApplication = true
      this.showAdd = false
      this.xyForm = {}
      this.bmForm = {
        day: dayjs(new Date()).format('YYYY-MM-DD'),
        courseType: '4'
      }
      this.tgMemberInfo = {}
      this.members = []
      this.pdSj = false
      this.getKcList()
      this.$nextTick(() => {
        this.$refs.memberSearchRef.clearSearch()
        this.$refs.bmForm.clearValidate()
      })
    },
    orderSuccess() {
      this.closeDrawer()
      this.isShowOrder = false
    },
    showAddBtn() {
      this.showStudent = true
      this.formStudent = {}
    },
    // PC预约课程信息
    getreserveClassInfoPC() {
      const param = { ...this.bmForm }
      const arr = [...this.perKcList]

      if (param.courseId) {
        const temp = arr.find(i => i.courseId === param.courseId)
        this.acticeKc = { ...temp }
      } else {
        this.acticeKc = {}
      }

      if (param.courseId) {
        if (param.day) {
          this.getTeacherList()
        }
        arr.forEach(s => {
          if (s.courseId === param.courseId) {
            if (s.courseType !== '4') {
              this.pdSj = false
              let memberLength = 0
              if (param.members && param.members.length > 0) {
                memberLength = param.members.length
                let price = ''
                price = (s.price * memberLength).toFixed(2)
                this.$set(this.bmForm, 'price', price)
              } else {
                this.$set(this.bmForm, 'price', '')
              }
            } else {
              this.$set(this.bmForm, 'price', '')
              this.pdSj = true
            }
            this.$refs.bmForm.clearValidate()
          }
        })
      }
      if (param.courseType === '5' || param.courseType === 5) {
        return false
      }
      if (!param.courseId || !param.teacherId || !param.day) {
        this.timeList = []
        return
      }
      reserveClassInfoPC({
        param
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.timeList = res.record.timeInfos || []
            arr.forEach(s => {
              if (s.courseId === param.courseId && s.courseType === '4') {
                let memberLength = 0
                let priceb = ''
                if (param.members && param.members.length > 0) {
                  memberLength = param.members.length
                  if (param.time && param.time.length > 0) {
                    priceb = (res.record.price * memberLength * param.time.length).toFixed(2)
                    this.$set(this.bmForm, 'price', priceb)
                    this.$refs.bmForm.clearValidate()
                  }
                }
              }
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    confirmAction() {
      const that = this
      const timeList = [...this.timeList]
      const param = { ...this.bmForm }
      const memberInfo = { ...this.tgMemberInfo }
      memberInfo.remainingMoney = memberInfo.rechargeMoney
      memberInfo.remainingGiveMoney = memberInfo.giveMoney
      const privateCourseTimeInterval = []
      const time = param.time || []
      this.$refs.bmForm.validate((valid) => {
        if (valid) {
          timeList.forEach((a, index) => {
            time.forEach((b) => {
              if (b === index) {
                privateCourseTimeInterval.push({
                  startPeriodTime: a.startTime,
                  endPeriodTime: a.endTime
                })
              }
            })
          })
          param.privateCourseTimeInterval = privateCourseTimeInterval
          param.phone = memberInfo.phone
          param.userName = memberInfo.nickName
          param.memberInfo = memberInfo
          param.sjFlag = '1'
          param.students = param.members.join()
          that.isShowOrder = true
          that.$nextTick(() => {
            this.subLoading = true
            try {
              that.$refs.orderRef.continuePay(param, 'studentAdd')
            } catch (error) {
              this.subLoading = false
            }
            setTimeout(() => {
              this.subLoading = false
            }, 3000)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 课程列表
    getKcList() {
      const venueIds = [sessionStorage.getItem('venueId')]
      publishCourseList({ param: { venueIds, channel: '02', courseType: this.bmForm.courseType, flag: '2' }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.perKcList = res.recordList || []
          this.perKcList.map(item => {
            item.numJoin = item.numJoin || 0
            return item
          })
        })
    },
    onSubmitb() {
      const param = { ...this.formStudent }
      if (!param.name) {
        this.$message.error(this.$t('message.qsr') + this.$t('message.xyxm'))
        return
      }
      if (param.birthday) {
        param.birthday = param.birthday + ' 00:00:00'
      }
      if (param.idCard2) {
        param.idCard = param.idCard2
      }
      param.memberId = this.tgMemberInfo.id
      this.subStuLoading = true
      studentAdd({
        param
      })
        .then((res) => {
          this.subStuLoading = false
          if (res.errorCode === '000000') {
            this.$message.success(this.$t('message.tjcg2'))
            this.showStudent = false
            this.getStuList()
          }
        })
        .catch((err) => {
          this.subStuLoading = false
          console.log(err)
        })
    },
    closeDrawer() {
      this.tgMemberInfo = {}
      this.$refs.memberSearchRef.clearSearch()
      this.$set(this.bmForm, 'memberId', '')
      this.$refs.bmForm.clearValidate()
      this.showApplication = false
      // this.$emit('close')
    },
    tgMemberClear() {
      this.tgMemberInfo = {}
    },
    tgMemberSelect(item) {
      const fn = () => {
        this.tgMemberInfo = item
        this.getStuList()
        this.$set(this.bmForm, 'memberId', item.id)
        this.$refs.bmForm.clearValidate()
      }
      fn()
    },
    getStuList() {
      studentListByMember({
        param: {
          memberId: this.tgMemberInfo.id
        }
      })
        .then(res => {
          // console.log(res)
          this.members = res.recordList || []
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 上课教练
    getTeacherList() {
      const venueId = sessionStorage.getItem('venueId')
      const param = { ...this.bmForm }
      teacherGmList({
        param: {
          venueId,
          day: param.day,
          courseId: param.courseId
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.teachList = res.recordList || []
        })
        .catch(() => { })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.acticeKc_wrap{
  display: flex;
  flex-wrap: wrap;
  padding: 16px 12px;
  background-color: #f7f7f7;
  .item{
    width: 50%;
    line-height: 24px;
  }
}
</style>
